package pc

import (
	. "chess_platform/internal/common"
	"fmt"
	"github.com/astaxie/beego/orm"
)

func NewCardTest(data map[string]interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessSysData)
	values, sql := InsertSql(TableCardTest, data)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

func UpdateCardTest(data map[string]interface{}, id int64) error {
	o := NewDBOrm(DBChessSysData)
	condition := fmt.Sprintf(`id = %v`, id)
	values, sql := UpdateSql(TableCardTest, data, condition)
	_, err := o.Raw(sql, values).Exec()
	return err
}

func CardTestInfoById(id int64) (*CardTest, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			id = %v
		LIMIT 1
		`, TableCardTest, id)
	o := NewDBOrm(DBChessSysData)
	var data CardTest
	err := o.Raw(sql).QueryRow(&data)
	if CheckNoExist(err) {
		return nil, nil
	}
	return &data, err
}

func ListCardTest(p ListParams) ([]*CardTest, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	o := NewDBOrm(DBChessSysData)
	sql := fmt.Sprintf(`
			SELECT
				*
			FROM
				%v
			LIMIT ?,?
		`, TableCardTest)
	var data []*CardTest
	_, err := o.Raw(sql, limit, p.PageSize).QueryRows(&data)
	if err != nil {
		return nil, 0, err
	}
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v `, TableCardTest)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	return data, count, err
}

func DeleteCardTest(id int64) (int64, error) {
	o := NewDBOrm(DBChessSysData)
	condition := fmt.Sprintf("id = %v", id)
	sql := DeleteSql(TableCardTest, condition)
	result, err := o.Raw(sql).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}
